//
//  PersonalDataVCtrol.m
//  jingdongfang
//
//  Created by 郝志宇 on 16/6/24.
//  Copyright © 2016年 XuDong Jin. All rights reserved.
//

#import "PersonalDataVCtrol.h"
#import "NickViewController.h"
#import "MosViewController.h"
#import "AddressViewController.h"
#import "PhotoUpLoadAgreementViewController.h"
#import "UserUNidentyViewController.h"
#import "IGGetMyinfoApi.h"
#import "SVProgressHUD.h"
#import "IGOSSManager.h"
#import "IGUpdateImageApi.h"

@interface PersonalDataVCtrol () <UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, UINavigationControllerDelegate> {
    UIImageView *icon;
    NSString *klanguage ;
}

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (nonatomic, strong) IGGetMyinfoApi *myApi;
@property (nonatomic, strong) IGAuthen *authen;


@end

@implementation PersonalDataVCtrol
#pragma mark -生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"个人资料";
    self.title = NSLocalizedString(@"Profile", nil);
    self.table.backgroundColor=[UIColor c2Color];
    klanguage = [[NSUserDefaults standardUserDefaults] objectForKey:KLanguage];
    [[IGOSSManager sharedManager] requestOssToken:IGAliYunFolderTypeUser];
}

-(void)loadUserinfoData{
    self.myApi = [IGGetMyinfoApi new];
    [self.myApi startWithDecodeClass:[IGGetMyinfoResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGGetMyinfoResp *resp = responseObject;
            IGGetMyinfoModel *model = resp.data;
            IGUserInfo *userInfo = model.member;
            _authen = userInfo.authen;
            [IGUser saveUserInfo:userInfo];
            [self.table reloadData];
        }
    }];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadUserinfoData];
}

#pragma mark — UITableViewDelegate, UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 4;
    } else if (section == 1) {
        return 2;
    }
    else if (section == 2) {
        return 1;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.font = [UIFont font16];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
    cell.detailTextLabel.textColor = [UIColor grayColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section==0) {
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        if (indexPath.row==0) {
//            cell.textLabel.text = @"头像";
            cell.textLabel.text = NSLocalizedString(@"Image", nil);
            icon = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 45, 45)];
            [icon sd_setImageWithURL:[NSURL URLWithString:[IGUser getImage]] placeholderImage:[UIImage imageNamed:@"place_head_Icon"]];
            icon.layer.cornerRadius = icon.width/2;
            icon.layer.masksToBounds = YES;
            icon.contentMode = UIViewContentModeScaleAspectFill;
            icon.clipsToBounds = YES;
            icon.backgroundColor = [UIColor appColor];
            cell.accessoryView = icon;
        } else if (indexPath.row==1) {
            cell.textLabel.text = @"ID";
            cell.userInteractionEnabled=NO;
            cell.detailTextLabel.text = [IGUser getUid];
        } else if (indexPath.row==2) {
//            cell.textLabel.text = @"昵称";
            cell.textLabel.text = NSLocalizedString(@"Nickname", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.detailTextLabel.text = [IGUser getNike];
        } else if (indexPath.row==3) {
//            cell.textLabel.text = @"简介";
            cell.textLabel.text = NSLocalizedString(@"Intro", nil);

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
    } else if (indexPath.section==1) {
        if (indexPath.row==0) {
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
//            cell.textLabel.text = @"身份认证";
            cell.textLabel.text = NSLocalizedString(@"Identity authentication", nil);

            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            if ([[IGUser getAuthens] integerValue] == 1) {
//                cell.detailTextLabel.text = @"未认证";
                cell.detailTextLabel.text = NSLocalizedString(@"Unverified", nil);

            } else if([[IGUser getAuthens] integerValue] == 2) {
//                cell.detailTextLabel.text = @"通过";
                cell.detailTextLabel.text = NSLocalizedString(@"Passed", nil);
                cell.accessoryType=UITableViewCellSelectionStyleNone;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
            } else if ([[IGUser getAuthens] integerValue] == 3) {
//                cell.detailTextLabel.text = @"待认证";
                cell.detailTextLabel.text = NSLocalizedString(@"To be Verified", nil);

                cell.detailTextLabel.textColor = [UIColor redColor];
                cell.accessoryType=UITableViewCellSelectionStyleNone;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
            } else if([[IGUser getAuthens] integerValue] == 4) {
//                cell.detailTextLabel.text = @"未通过";
                cell.detailTextLabel.text = NSLocalizedString(@"Rejected", nil);

                cell.detailTextLabel.textColor = [UIColor redColor];
                cell.detailTextLabel.font=[UIFont font14];
            }
        } else if (indexPath.row==1) {
//            cell.textLabel.text = @"帐号类型";
            cell.textLabel.text = NSLocalizedString(@"Account Type", nil);

            if ([[IGUser getType] integerValue] == 0) {
//                cell.detailTextLabel.text = @"手机号";
                cell.detailTextLabel.text = NSLocalizedString(@"Mobile Number", nil);

            } else if ([[IGUser getType] integerValue] == 1) {
//                cell.detailTextLabel.text = @"微信";
                cell.detailTextLabel.text = NSLocalizedString(@"WeChat", nil);

            } else if ([[IGUser getType] integerValue] == 2) {
                cell.detailTextLabel.text = @"QQ";
//                cell.detailTextLabel.text = NSLocalizedString(@"", nil);

            } else if ([[IGUser getType] integerValue] == 3) {
//                cell.detailTextLabel.text = @"新浪";
                cell.detailTextLabel.text = NSLocalizedString(@"Weibo", nil);

            }else if([[IGUser getType] integerValue] == 4){
//                cell.detailTextLabel.text = @"平台用户";
                cell.detailTextLabel.text = NSLocalizedString(@"Platform Users", nil);

            }
        }
    } else if (indexPath.section==2) {
        if (indexPath.row==0) {
//            cell.textLabel.text = @"收货地址";
            cell.textLabel.text = NSLocalizedString(@"Recipient Address", nil);
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleGray;
            if([klanguage containsString:@"en"]){
                cell.hidden=YES;
            }
        }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    @KWeakObj(self)
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            [IGPermissionUtil ig_showActionSheetWithCameraBlock:^{
                [IGTakePhotosUtil ig_showImagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera isAllowEdit:YES imagePickerBlock:^(NSDictionary<NSString *,id> * _Nullable info) {
                    if (info) {
                        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
                        image = [image fixOrientation];
                        [selfWeak uploadToAliyun:@[image]];
                    }
                }];
            } photoBlock:^{
                [IGTakePhotosUtil ig_showAssetsPickerControllerWithIsAllowEdit:YES assetsPickerBlock:^(NSArray<UIImage *> * _Nullable assets) {
                    if (assets.count != 0) {
                        UIImage *image = assets[0];
                        [selfWeak uploadToAliyun:@[image]];
                    }
                }];
            }];
        } else if (indexPath.row==2) {
            NickViewController *vc = [[NickViewController alloc] init];
            vc.nick = [IGUser getNike];
            [UIViewController ig_pushViewController:vc animated:YES];
        } else if (indexPath.row==3) {
            MosViewController *vc = [[MosViewController alloc] init];
            vc.context = [IGUser getContent];
            [UIViewController ig_pushViewController:vc animated:YES];
        }
    }else if(indexPath.section==1){
        if (indexPath.row==0) {
            if ([[IGUser getAuthens] integerValue] == 1) {
                PhotoUpLoadAgreementViewController *photoAgreenmentVC = [[UIStoryboard storyboardWithName:@"UserCertification" bundle:nil] instantiateViewControllerWithIdentifier:@"PhotoUpLoadAgreementViewController"];
                [UIViewController ig_pushViewController:photoAgreenmentVC animated:YES];
            } else if([[IGUser getAuthens] integerValue] == 4) {
                //审核未通过
                UserUNidentyViewController *vc=[[UserUNidentyViewController alloc]initWithNibName:@"UserUNidentyViewController" bundle:nil];
                vc.content = _authen.content;
                [UIViewController ig_pushViewController:vc animated:YES];
            }
        }
    } else if(indexPath.section==2){
        if (indexPath.row==0) {
            [UIViewController ig_pushViewControllerClass:[AddressViewController class] animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 12.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55.f;
}
//上传到阿里云
- (void)uploadToAliyun:(NSArray *)images {
//    [self showText:@"正在提交..."];
    [self showText:NSLocalizedString(@"Submitting", nil)];
    [[IGOSSManager sharedManager] asyncPutImages:images withCompleteBlock:^(NSArray *params, NSArray *urls) {
        if (params.count != 0)  {
            [self updataImga:params.firstObject];
        } else  {
//            [self presentMessageTips:@"提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Submitting Failed", nil)];
        }
    }];
}

- (void)updataImga:(NSString *)str
{
    IGUpdateImageApi *api = [IGUpdateImageApi new];
    api.image = str;
    [api startWithDecodeClass:[IGUpdateImageResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [icon sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"place_head_Icon"]];
            
                [IGUser saveImage:str];
//                [self presentMessageTips:@"提交成功"];
                [self presentMessageTips:NSLocalizedString(@"Upload image successfully", nil)];
            });
        } else {
//            [self presentMessageTips:@"提交失败"];
            [self presentMessageTips:NSLocalizedString(@"Submitting Failed", nil)];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
